<template>
  <div class="after-class-info">
    <div ref="chart" style="width: 100%; height: 100%;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'RankingChart',
  data() {
    return {
      ranking1: require('@/assets/04.png'),
      ranking2: require('@/assets/04.png'),
      ranking3: require('@/assets/04.png'),
      ranking4: require('@/assets/04.png'),
      newStudentId: "",
      afterClassInfo: [],
      dataZoomMove: {
        start: 0,
        end: 3 // 只显示3个（索引0-2）
      },
      dataZoomMoveTimer: null,
      myChart: null
    }
  },
  props: ["studentId"],
  watch: {
    studentId: {
      immediate: true, // 立即触发一次
      handler(newValue) {
        if (newValue) {
          this.getAfterClassInfoById(newValue);
        }
      },
    },
  },
  computed: {
    option() {
      return {
        legend: {
          show: false
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            shadowStyle: {
              color: 'rgba(255, 255, 255, 0.1)',
              width: 'auto'
            }
          },
          backgroundColor: 'rgba(0, 0, 0, 0.1)',
          borderColor: '#14F7FF',
          borderWidth: 2,
          borderRadius: 4,
          padding: [10, 15],
          textStyle: {
            color: '#14F7FF',
            fontSize: 14,
            fontWeight: 'bold',
            fontFamily: 'Microsoft YaHei'
          },
          extraCssText: `
            box-shadow: 0 0 15px rgba(20, 247, 255, 0.4);
            backdrop-filter: blur(5px);
            border-image: linear-gradient(45deg, #14F7FF, #063863) 1;
          `,
          confine: true,
          formatter: (params) => {
            const data = params[0].data;
            return `<div style="position: relative;">
                      <div style="
                        position: absolute;
                        left: -15px;
                        top: 50%;
                        transform: translateY(-50%);
                        width: 4px;
                        height: 20px;
                        background: linear-gradient(to bottom, #14F7FF, #063863);
                        border-radius: 2px;
                      "></div>
                      <div style="
                        padding-left: 10px;
                        border-left: 1px solid rgba(20, 247, 255, 0.3);
                      ">
                        <div style="margin-bottom: 5px; color: #fff;">任务${params[0].name}</div>
                        <div style="color: #14F7FF; font-size: 16px;">${data}分</div>
                      </div>
                    </div>`;
          }
        },
        grid: {
          left: '25%',
          right: '20%',
          top: '10%',
          bottom: '10%'
        },
        xAxis: { show: false },
        yAxis: [
          {
            gridIndex: 0,
            position: 'left',
            splitLine: {
              show: false
            },
            axisLine: {
              show: false
            },
            type: 'category',
            axisTick: {
              show: false
            },
            inverse: true,
            data: this.afterClassInfo.map((item, index) => index + 1),
            axisLabel: {
              align: 'left',
              padding: [0, 0, 0, -90],
              formatter: (index) => {
                const id = index;
                if (id < 4) {
                  return `{icon${id}|${id}}`;
                } else {
                  return `{count|${id}}`;
                }
              },
              rich: {
                icon1: {
                  width: 21,
                  padding: [0, 5, 0, 0],
                  height: 20,
                  fontSize: 12,
                  color: '#fff',
                  align: 'center',
                  borderRadius: 50,
                  backgroundColor: {
                    image: this.ranking1
                  }
                },
                icon2: {
                  width: 21,
                  padding: [0, 5, 0, 0],
                  height: 20,
                  color: '#fff',
                  fontSize: 12,
                  align: 'center',
                  borderRadius: 50,
                  backgroundColor: {
                    image: this.ranking2
                  }
                },
                icon3: {
                  width: 21,
                  padding: [0, 5, 0, 0],
                  height: 20,
                  color: '#fff',
                  fontSize: 12,
                  align: 'center',
                  backgroundColor: {
                    image: this.ranking3
                  }
                },
                count: {
                  width: 21,
                  height: 20,
                  color: '#fff',
                  fontSize: 12,
                  padding: [0, 5, 0, 0],
                  align: 'center',
                  backgroundColor: {
                    image: this.ranking4
                  }
                }
              }
            }
          },
          {
            gridIndex: 0,
            position: 'left',
            splitLine: {
              show: false
            },
            axisLine: {
              show: false
            },
            type: 'category',
            axisTick: {
              show: false
            },
            inverse: true,
            data: this.afterClassInfo.map((item) => item.name),
            axisLabel: {
              align: 'center',
              padding: [0, 0, 0, -30],
              formatter: (name) => {
                const paramsNameNumber = name.length;
                const provideNumber = 3; // 一行显示几个字
                return paramsNameNumber > provideNumber
                  ? name.substring(0, 3) + '...'
                  : name;
              },
              rich: {
                name: {
                  width: 70,
                  color: '#fff',
                  height: 25,
                  align: 'left',
                  fontSize: 14
                }
              }
            }
          },
          {
            type: 'category',
            inverse: true,
            splitLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            },
            data: this.afterClassInfo.map((item) => item.num),
            axisLabel: {
              verticalAlign: 'bottom',
              align: 'right',
              padding: [0, -60, -5, 0],
              textStyle: {
                color: '#14F7FF',
                fontSize: 14
              },
              formatter: (value) => value + '分'
            }
          }
        ],
        dataZoom: [
          {
            show: false,
            realtime: true,
            type: 'slider',
            height: '90%',
            startValue: this.dataZoomMove.start,
            endValue: this.dataZoomMove.end,
            width: 6,
            right: '26%',
            top: '1%',
            yAxisIndex: [0, 1, 2],
            moveHandleStyle: {
              color: 'rgba(89, 202, 241,.5)'
            },
            moveHandleSize: '6',
            emphasis: {
              moveHandleStyle: {
                color: 'rgba(89, 202, 241,.5)'
              }
            },
            textStyle: {
              color: 'rgba(255,255,255,0)'
            },
            backgroundColor: 'rgba(255,255,255,.1)',
            borderColor: 'rgba(255,255,255,0)',
            fillerColor: 'rgba(0,0,0,0)',
            handleSize: '6',
            handleStyle: {
              color: 'rgba(255,255,255,0)'
            },
            brushStyle: {
              color: 'rgba(129, 243, 253)'
            }
          },
          {
            type: 'inside',
            yAxisIndex: 0,
            zoomOnMouseWheel: false,
            moveOnMouseMove: true,
            moveOnMouseWheel: true
          }
        ],
        series: [
          {
            name: '分数',
            type: 'bar',
            barWidth: 12,
            showBackground: true,
            barGap: '21.5%',
            barCategoryGap: '21.5%',
            backgroundStyle: {
              color: 'rgba(58,69,75, 1)',
              borderRadius: 30
            },
            itemStyle: {
              borderRadius: 30,
              borderWidth: 2,
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#063863' },
                { offset: 1, color: '#14F7FF' }
              ])
            },
            emphasis: {
              scale: true
            },
            data: this.afterClassInfo.map((item) => item.num)
          }
        ]
      };
    }
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (this.dataZoomMoveTimer) {
      clearInterval(this.dataZoomMoveTimer);
    }
    if (this.myChart) {
      this.myChart.dispose();
    }
  },
  methods: {
    getAfterClassInfoById(id) {
      this.$axios
        .get("/students/getAfterClassInfoById/" + id)
        .then((res) => {
          this.afterClassInfo = [...res.data.data]
            .map((item) => ({
              ...item,
              name: "任务" + Number(item.name),
            }))
            .sort((a, b) => {
              return (
                Number(a.name.replace("任务", "")) -
                Number(b.name.replace("任务", ""))
              );
            });
          
          // 重置轮播状态
          this.dataZoomMove.start = 0;
          this.dataZoomMove.end = 3;
          
          this.initChart();
        })
        .catch(error => {
          console.error('获取数据失败:', error);
          this.afterClassInfo = [];
          this.initChart();
        });
    },
    initChart() {
      if (this.myChart) {
        this.myChart.dispose();
      }
      
      this.myChart = echarts.init(this.$refs.chart);
      this.myChart.setOption(this.option);

      // 重置轮播状态
      this.dataZoomMove.start = 0;
      this.dataZoomMove.end = 3;

      // 清除之前的定时器
      if (this.dataZoomMoveTimer) {
        clearInterval(this.dataZoomMoveTimer);
        this.dataZoomMoveTimer = null;
      }

      // 只有当数据超过3条时才启动轮播
      if (this.afterClassInfo.length > 3) {
        this.startMoveDataZoom();
      }

      const chartDom = this.myChart.getDom();
      
      chartDom.addEventListener('mouseout', () => {
        if (this.dataZoomMoveTimer) return;
        const dataZoomMoveget = this.myChart.getOption().dataZoom[0];
        this.dataZoomMove.start = dataZoomMoveget.startValue;
        this.dataZoomMove.end = dataZoomMoveget.endValue;
        
        // 只有当数据超过3条时才重新启动轮播
        if (this.afterClassInfo.length > 3) {
          this.startMoveDataZoom();
        }
      }, { passive: true });

      chartDom.addEventListener('mouseover', () => {
        if (this.dataZoomMoveTimer) {
          clearInterval(this.dataZoomMoveTimer);
          this.dataZoomMoveTimer = null;
        }
      }, { passive: true });
    },
    startMoveDataZoom() {
      this.dataZoomMoveTimer = setInterval(() => {
        if (this.afterClassInfo.length <= 3) {
          clearInterval(this.dataZoomMoveTimer);
          this.dataZoomMoveTimer = null;
          return;
        }

        this.dataZoomMove.start += 1;
        this.dataZoomMove.end += 1;

        if (this.dataZoomMove.end >= this.afterClassInfo.length) {
          this.dataZoomMove.start = 0;
          this.dataZoomMove.end = 3;
        }

        this.myChart.setOption({
          dataZoom: [
            {
              startValue: this.dataZoomMove.start,
              endValue: this.dataZoomMove.end
            }
          ]
        });
      }, 3000);
    }
  }
};
</script>
<style>
.after-class-info {
  height: 90%;
  margin-top: -3%;
}
</style>